package com.e2oto.seller.common.http;


import com.e2oto.seller.common.base.BaseBean;
import com.e2oto.seller.widget.stateLayout.CommonStateLayout;
import com.e2oto.seller.widget.stateLayout.IStateLayout;

import java.net.ConnectException;
import java.net.SocketTimeoutException;

import io.reactivex.observers.DisposableObserver;


/**
 * Created by ZhangLiQiang on 2017/8/1.
 */


public class StateLayoutSubscriber<T> extends DisposableObserver<BaseBean<T>> {

    private StateLayoutSubscriberOnNextListener<T> mListener;
    private IStateLayout stateLayout;

    public StateLayoutSubscriber(StateLayoutSubscriberOnNextListener<T> listener, CommonStateLayout stateLayout) {
        this.mListener = listener;
        this.stateLayout = stateLayout;
    }


    @Override
    public void onError(Throwable e) {
        if (e instanceof SocketTimeoutException) {
            stateLayout.showErrorView();
        } else if (e instanceof ConnectException) {
            stateLayout.showErrorView();
        } else {
            stateLayout.showErrorView();
        }
    }

    @Override
    public void onComplete() {

    }

    @Override
    protected void onStart() {
        super.onStart();
        stateLayout.showLoadingView();
    }


    @Override
    public void onNext(BaseBean<T> baseBean) {

        if (mListener != null) {
            switch (baseBean.getCode()) {
                case 2000:
                    stateLayout.showContentView();
                    mListener.onNext(baseBean.getData());
                    break;
                case 3000:
                case 4000:
                case 5000:
                        stateLayout.showErrorView();
                    break;
            }

        } else {
            throw new NullPointerException("ProgressSubscriberOnNextListener is null");
        }
    }

}